package com.lipuwater.agent.service;

import android.Manifest;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.ismartlib.framework.permissions.Permission;
import com.ismartlib.framework.permissions.PermissionsResult;
import com.ismartlib.framework.permissions.ResultCallBack;
import com.ismartlib.utils.ActivityList;
import com.lipuwater.agent.app.config.AppConfig;
import com.lipuwater.agent.http.ApiCallBack;
import com.lipuwater.agent.http.HttpConfig;
import com.lipuwater.agent.http.ResponseParams;
import com.lipuwater.agent.http.api.ApiRequestsOther;
import com.lipuwater.agent.http.bean.app.AppInfoBean;
import com.lipuwater.agent.ui.dialog.AppUpdataDialog;
import com.lipuwater.agent.ui.dialog.DownLoadProgressDialog;
import com.lipuwater.agent.utils.DateUtils;
import com.lipuwater.agent.utils.MapToBeanUtil;
import com.lipuwater.agent.utils.ThreadUtils;
import com.lipuwater.agent.utils.preferences.PreferenceKey;
import com.lipuwater.agent.utils.preferences.PreferencesUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

import static android.content.Context.DOWNLOAD_SERVICE;
import static android.support.v4.content.FileProvider.getUriForFile;

/**
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃永无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * Created by  Administrator  on 2017/4/13.
 * Email:924686754@qq.com
 * 不使用service了，因为
 */
public class AppVersionUpdate/* extends Service*/ {
    private Context mContext;
    private AppUpdataDialog dialog;
    private boolean force = false;//是否强制更新
    private String apkurl = "";    //下载的apk url
    private int versionCode;
    private String apkPath;    //apk下载路径
    private String apkName;
    private String token;

    private DownloadManager mDownloadManager;
    private DownloadManager.Query mDownLoadQuery;
    private long mDownloadId;
    private int mDownProgress;

    public AppVersionUpdate(Context context, String token) {
        this.mContext = context;
        this.token = token;
        getVersionCode();
    }

    private void getVersionCode() {
        Map<String, Object> params = new HashMap<>();
        params.put("type", 1);
        params.put("token", token);
        ApiRequestsOther.appVersionUpdate(this, params, new ApiCallBack() {
            @Override
            public void onResponse(ResponseParams result) {
                if (result.getStatus() == HttpConfig.success) {
                    try {
                        AppInfoBean appInfo = (AppInfoBean) MapToBeanUtil.toJavaBean(result.getParams().get("appInfo"), AppInfoBean.class);
                        if (appInfo.getVersionCode() > AppConfig.LOCAL_VERSION) {
                            if ((int) (PreferencesUtils.getInstance().getParam(PreferenceKey.IGNORE_VERSION, 0)) == appInfo.getVersionCode()) {
                                return;
                            }
                            force = appInfo.getForce() == 2 ? true : false;
                            versionCode = appInfo.getVersionCode();
                            apkurl = appInfo.getPackageUrl();
                            //apkurl = "http://119.147.33.14/imtt.dd.qq.com/16891/431A3CCCBD7E7F1AB1979EFB26235BF0.apk?mkey=593b5b895f1d6784&f=301d&c=0&fsname=com.taobao.taobao_6.8.0_155.apk&csr=1bbd&p=.apk";
                            String content = "版本：" + appInfo.getVersionName() + "  " + "大小：" + appInfo.getPackageSize() / 1000 + "M"
                                    + "\n时间：" + DateUtils.getFriendlyDate(appInfo.getTimestamp())
                                    + "\n" + appInfo.getUpdateInfo();
                            showDialog(content);
                        }
                    } catch (Exception e) {
                    }
                }
            }

            @Override
            public void onError(Call call, Exception e) {

            }
        });
    }

    private void showDialog(String content) {
        dialog = new AppUpdataDialog(mContext, force, versionCode, content, new AppUpdataDialog.DialogClickListener() {
            @Override
            public void onLeftBtnClick(Dialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onRightBtnClick(Dialog dialog) {
                try {
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        apkPath = AppConfig.APP_SDCARD_DIR;
                        apkName = "LIPU.apk";
                        if (force) {
                            //强制更新的话为了防止用户关闭
                            new DownLoadProgressDialog(mContext, apkurl, apkPath, apkName, new DownLoadProgressDialog.callback() {
                                @Override
                                public void onResults(boolean results) {
                                    if (results) {
                                        installApk();
                                    }
                                }
                            }).show();
                        } else {
                            requestPermission();//下载Apk
                        }
                        force = false;
                        dialog.dismiss();
                    } else {
                        Toast.makeText(mContext, "下载失败，SD卡不存在", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                }

            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (force) {
                    //强制更新，不能取消
                    ActivityList.getInstance().exit();
                }
            }
        });
        dialog.show();
    }

    private void requestPermission() {
        Permission.getInstance(mContext)
                .requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .results(new ResultCallBack() {
                    @Override
                    public void result(PermissionsResult result) {
                        if (result.getPermission().equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && result.isGranted()) {
                            downloadApk(apkurl, apkPath);
                        } else {
                            new AlertDialog.Builder(mContext).
                                    setTitle("帮助")
                                    .setMessage("请在设置->应用管理->力浦净水->权限管理->读写手机存储\n避免影响正常功能的使用")
                                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Uri packageURI = Uri.parse("package:" + mContext.getPackageName());
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                            mContext.startActivity(intent);
                                        }
                                    }).setNegativeButton("取消", null).show();
                        }
                    }
                });
    }

    private void downloadApk(String url, String filePath) {
        //實時獲取下載進度
        ThreadUtils.getInstance().getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                while (mDownProgress < 101) {
                    try {
                        Thread.sleep(200);
                        getDownLoadProgress();
                        if (mDownProgress == 100) {
                            mDownProgress++;
                            installApk();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        if (mDownloadManager == null) {
            mDownloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
        }
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File apk = new File(filePath, apkName);
        if (apk.exists()) {
            apk.delete();
        }
        File file = new File(dir, apkName);
        request.setDestinationUri(Uri.fromFile(file));
        mDownloadId = mDownloadManager.enqueue(request);
    }

    /**
     * 獲取下載進度
     *
     * @return
     */
    private int getDownLoadProgress() {
        if (mDownloadManager == null) {
            mDownloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
        }
        if (mDownLoadQuery == null) {
            mDownLoadQuery = new DownloadManager.Query().setFilterById(mDownloadId);
        }
        Cursor cursor = null;
        try {
            cursor = mDownloadManager.query(mDownLoadQuery);
            if (cursor != null && cursor.moveToFirst()) {
                //当前的下载量
                int downloadSofar = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //文件总大小
                int totalBytes = cursor.getInt(
                        cursor.getColumnIndexOrThrow(
                                DownloadManager.COLUMN_TOTAL_SIZE_BYTES
                        ));
                mDownProgress = (int) (downloadSofar * 1.0f / totalBytes * 100);
            } else {
                //下載出錯
                mDownProgress = 101;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return mDownProgress;
    }

    /**
     * 安装apk
     */
    private void installApk() {
        //兼容AndroidN
        File apkfile = new File(apkPath, apkName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
            Uri apkUri = getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", apkfile); //与manifest中定义的provider中的authorities="com.xinchuang.buynow.fileprovider"保持一致
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            i.setDataAndType(apkUri, "application/vnd.android.package-archive");
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else {
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                    "application/vnd.android.package-archive");
        }
        mContext.startActivity(i);
    }

    /* manager = (NotificationManager) mContext.getSystemService(Service.NOTIFICATION_SERVICE);

        notification = new Notification.Builder(mContext);
        notification.setSmallIcon(R.drawable.logo)
                .setTicker("showProgressBar")
                .setOngoing(true).setContentTitle("版本更新")
                .setContentText("正在下载");
        manager.notify(0, notification.build());*/
       /* notification.setProgress(100, progress, false);
        manager.notify(0, notification.build());

        notification.setContentText("下载完成")
                .setProgress(0, 0, false).setOngoing(false);
        manager.notify(0, notification.build());*/

}
